﻿Imports BusinessLayer
Imports CommonLayer
Imports System.ComponentModel
Imports Infragistics.Win.UltraWinToolbars
Imports Infragistics.Win.UltraWinGrid
Imports System.Data.SqlClient

Public Class frmBaseDictionaryList

#Region "Declaration"

    Protected eActionMode As EditMode
    Private m_strCodeColumnName As String
    Private m_strKeyObjectName As String = ""
    Protected m_sTableName As String

    Protected oBLDictionary As BLDictionary

    Protected m_dsDictionary As DataSet
    'Private Const mscSQLExceptionContrainsNumber As Integer = 547
    Private m_sPrimaryKeyColumnName As String

    Private IsLoadingData As Boolean = False

#End Region

#Region "Property"

    Public Overridable ReadOnly Property PermissionID() As PermissionEnum
        Get
            Return Nothing
        End Get
    End Property

#Region "Show/Hide Tool "

    <Description("The Field name stored Alias of the dictionary"), Category("MySoft")> _
    Public Property CodeColumnName() As String
        Get
            Return m_strCodeColumnName
        End Get
        Set(ByVal Value As String)
            m_strCodeColumnName = Value
        End Set
    End Property

    <Description("The field name stored Object name"), Category("MySoft")> _
    Public Property KeyObjectName() As String
        Get
            Return m_strKeyObjectName
        End Get
        Set(ByVal value As String)
            m_strKeyObjectName = value
        End Set
    End Property

    <Description("The primary key of the dictionary"), Category("MySoft")> _
    Public Property PrimaryKeyColumnName() As String
        Get
            Return m_sPrimaryKeyColumnName
        End Get
        Set(ByVal Value As String)
            m_sPrimaryKeyColumnName = Value
        End Set
    End Property

    <Description("Table name of dictionary"), Category("MySoft")> _
    Public Property TableName() As String
        Get
            Return m_sTableName
        End Get
        Set(ByVal value As String)
            m_sTableName = value
        End Set
    End Property

    <Description("Dataset of dictionary"), Category("MySoft")> _
    Public Property DictionaryData() As DataSet
        Get
            Return m_dsDictionary
        End Get
        Set(ByVal value As DataSet)
            m_dsDictionary = value
        End Set
    End Property

#End Region

#End Region

#Region "Constructor"

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
    End Sub

#End Region

#Region "Method"

#Region "Private Method"

#End Region

#Region "Public Method"


#Region "Init Data"

    Public Overridable Sub InitPublicObject()
        If Not Me.DesignMode Then
            oBLDictionary = New BLDictionary
            With oBLDictionary
                .BusinessObject = m_dsDictionary
                .TableName = m_sTableName
            End With
        End If
    End Sub

    ''' <summary>
    ''' Hien thi du lieu cho cac combo
    ''' </summary>
    Protected Overridable Sub InitDataToCombo()
    End Sub

    ''' <summary>
    ''' Hien thi du lieu cho Grid
    ''' </summary>
    Protected Overridable Sub InitGridData()
        IsLoadingData = True
        If Not oBLDictionary Is Nothing Then
            With oBLDictionary
                .BusinessObject.Tables(.TableName).Clear()
                .GetAllData()
            End With
            SetActiveRowAfterBinding()

            bsList.Sort = m_strCodeColumnName
        End If
        IsLoadingData = False
        BindingSourcePositionChanged()
    End Sub

    Protected Sub SetActiveRowAfterBinding()
        With grdList
            If .Rows.Count > 0 Then
                .ActiveRow = .Rows.GetRowAtVisibleIndex(1)
                .ActiveRow.Selected = True
                bsList.Position = bsList.IndexOf(.ActiveRow.ListObject)
            End If
        End With
    End Sub

    Protected Overridable Function InitAddNewRow() As DataRow
        Return Nothing
    End Function

#End Region


#Region "CRUD"

    Protected Friend Overridable Sub NewDictionary()
        If _
            Not _
            CommonFunction.CheckPermissionByID(CommonFunction.MySession.CurrentUser, Me.PermissionID, ActionEnum.AddNew) _
            Then
            Return
        End If
        eActionMode = EditMode.Add
        ShowFormDetail()
    End Sub

    Protected Friend Overridable Sub EditDictionary(ByVal isView As Boolean)
        If bsList.Position >= 0 Then
            If _
                Not _
                CommonFunction.CheckPermissionByID(CommonFunction.MySession.CurrentUser, Me.PermissionID, _
                                                   IIf(isView, ActionEnum.Use, ActionEnum.Edit)) Then
                Return
            End If

            eActionMode = IIf(isView, EditMode.View, EditMode.Edit)
            ShowFormDetail()
        End If
    End Sub

    ''' <summary>
    ''' Xóa dong Dictionary
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Friend Overridable Function DeleteDictionary() As Boolean
        Try
            Dim strDeletedErrMess As String = ""
            Dim sDictionaryCanNotDelete As String = ""

            If grdList.ActiveRow IsNot Nothing AndAlso grdList.ActiveRow.IsDataRow Then
                grdList.ActiveRow.Selected = True
            End If
            Dim bIsMultiDelete As Boolean = grdList.Selected.Rows.Count > 1

            If grdList.Selected.Rows.Count > 0 Then

                If _
                    Not _
                    CommonFunction.CheckPermissionByID(CommonFunction.MySession.CurrentUser, Me.PermissionID, _
                                                       ActionEnum.Delete) Then
                    Return False
                End If

                If _
                    CommonFunction.ShowQuestionMessage( _
                        IIf(bIsMultiDelete, My.Resources.Delete_Multy_Confirm_Alert, _
                            My.Resources.Delete_Single_Confirm_Alert), MessageBoxButtons.YesNo) = DialogResult.No Then
                    Exit Function
                Else
                    Dim guiID As Guid
                    Dim strPrimaryKey As String = oBLDictionary.PrimaryKey
                    Dim sValue As String = ""
                    Dim i As Integer = 0
                    Dim dr As DataRow = Nothing
                    Dim arrRow() As Object = grdList.Selected.Rows.All
                    Dim dtError As DataSetLocal.ErrorDeleteDataTable = Nothing
                    Dim drError As DataSetLocal.ErrorDeleteRow = Nothing

                    If bIsMultiDelete Then
                        dtError = New DataSetLocal.ErrorDeleteDataTable
                    End If

                    If arrRow IsNot Nothing AndAlso arrRow.Length > 0 Then
                        For Each row As UltraGridRow In arrRow
                            dr = CommonFunction.GetDataRow(row)
                            guiID = dr.Item(strPrimaryKey)

                            If dr.Table.Columns.Contains(m_strCodeColumnName) Then
                                sValue = dr.Item(m_strCodeColumnName)
                            End If

                            Try
                                If dr.Table.Columns.Contains("IsSystem") AndAlso dr.Item("IsSystem") Then
                                    If bIsMultiDelete Then
                                        drError = dtError.NewErrorDeleteRow
                                        drError.CodeValue = sValue
                                        drError.Description = "Bạn không thể xóa vì << " & sValue & _
                                                              " >> thuộc về hệ thống."
                                        dtError.AddErrorDeleteRow(drError)
                                    Else
                                        CommonFunction.ShowExclamation( _
                                            "Bạn không thể xóa vì << " & sValue & " >> thuộc về hệ thống.")
                                    End If
                                Else
                                    If Not oBLDictionary.DeleteRow(guiID) Then
                                        If bIsMultiDelete Then
                                            drError = dtError.NewErrorDeleteRow
                                            drError.CodeValue = sValue
                                            drError.Description = "Có lỗi xảy ra khi xóa << " & sValue & " >>."
                                            dtError.AddErrorDeleteRow(drError)
                                        End If
                                    Else
                                        row.Delete(False)
                                    End If
                                End If

                            Catch exSQL As SqlException
                                If exSQL.Number = CommonFunction.mscSQLExceptionContrainsNumber Then
                                    If bIsMultiDelete Then
                                        drError = dtError.NewErrorDeleteRow
                                        drError.CodeValue = sValue
                                        drError.Description = "Bạn không thể xóa vì << " & sValue & _
                                                              " >> đã có phát sinh."
                                        dtError.AddErrorDeleteRow(drError)
                                    Else
                                        CommonFunction.ShowExclamation( _
                                            "Bạn không thể xóa vì << " & sValue & " >> đã có phát sinh.")
                                    End If
                                End If
                            End Try

                        Next
                    End If

                    oBLDictionary.AcceptChange()

                    'If grdList.Rows.Count > 0 AndAlso (grdList.ActiveRow Is Nothing OrElse Not grdList.ActiveRow.IsDataRow) Then
                    '    grdList.ActiveRow = grdList.Rows(0)
                    '    grdList.ActiveRow.Selected = True
                    'End If

                    If dtError IsNot Nothing Then
                        dtError.AcceptChanges()
                        If dtError.Rows.Count > 0 Then
                            Dim frmError As New frmErrorDelete
                            With frmError
                                .Owner = Me
                                .CodeFieldCaption = _
                                    grdList.DisplayLayout.Bands(0).Columns(m_strCodeColumnName).Header.Caption
                                .DataSource.ErrorDelete.Clear()
                                .DataSource.ErrorDelete.Merge(dtError)
                                .ShowDialog()
                            End With
                            frmError = Nothing
                        End If
                    End If
                End If
            End If
            Return True
        Catch ex As Exception
            CommonFunction.ShowExceptionMessage(ex)
        End Try
    End Function

#End Region

#Region "Others"

    ''' <summary>
    ''' Get lastest data from databse
    ''' </summary>
    ''' <remarks>gtluc 07/08/2007</remarks>
    Protected Friend Overridable Sub RefreshData()
        InitGridData()
    End Sub

    Friend Overridable Function ShowFormDetail(Optional ByVal isGetCode As Boolean = False) As Object
        Dim drDictionary As DataRow = Nothing
        Dim oPrimaryKeyValue As Object = Nothing
        Dim sCodeValue As String = ""
        Dim strIDName As String = ""

        If Not oBLDictionary Is Nothing Then
            strIDName = oBLDictionary.PrimaryKey
            Select Case eActionMode
                Case EditMode.Add
                    'gdvBaseList..Rows.Clear()
                    drDictionary = InitAddNewRow()
                    'Khoi tao Row moi
                    oPrimaryKeyValue = drDictionary(strIDName)
                    bsList.Position = bsList.Find(strIDName, oPrimaryKeyValue)
                    oBLDictionary.CurrenceBusiness = drDictionary
                Case EditMode.View, EditMode.Edit
                    drDictionary = CommonFunction.GetCurrentRow(bsList)
                    oBLDictionary.CurrenceBusiness = drDictionary
            End Select
        End If

        Dim frm As frmBaseDictionaryDetail

        frm = GetFormDetail()
        If Not IsNothing(frm) Then
            With frm
                .ActionMode = eActionMode
                .DictionaryObject = oBLDictionary
                .DictionaryData = bsList
                .CodeColumnName = m_strCodeColumnName
                .DictionaryDataSet = dsDictionary
                .PrimaryKeyColumnName = m_sPrimaryKeyColumnName
                .CurrentRow = drDictionary
                .StartPosition = FormStartPosition.CenterScreen
                .WindowState = FormWindowState.Normal
                .Owner = Me
                If .ShowDialog() = DialogResult.OK Then
                    If _
                        drDictionary.RowState <> DataRowState.Detached AndAlso _
                        drDictionary.RowState <> DataRowState.Deleted Then
                        oPrimaryKeyValue = drDictionary(strIDName)

                        If _
                            Not IsNothing(Me.CodeColumnName) AndAlso _
                            drDictionary.Table.Columns.Contains(Me.CodeColumnName) Then
                            sCodeValue = drDictionary(Me.CodeColumnName)
                        End If
                    Else
                        If bsList.List.Count > 0 Then
                            oPrimaryKeyValue = CommonFunction.GetCurrentRow(bsList)(strIDName)
                            If _
                                Not IsNothing(Me.CodeColumnName) AndAlso _
                                CommonFunction.GetCurrentRow(bsList).Table.Columns.Contains(Me.CodeColumnName) Then
                                sCodeValue = CommonFunction.GetCurrentRow(bsList)(Me.CodeColumnName)
                            End If
                        Else
                            oPrimaryKeyValue = Nothing
                            sCodeValue = Nothing
                        End If

                    End If


                Else
                    'SetEnableButtonOnToolbar(grdList.Rows.FilteredInRowCount > 0)
                    oPrimaryKeyValue = Guid.Empty
                End If
            End With
        End If
        'frm.Dispose()
        frm = Nothing

        If isGetCode Then
            Return sCodeValue
        Else
            Return oPrimaryKeyValue
        End If
    End Function

#End Region


#End Region

#Region "Overridable"

    ''' <summary>
    ''' set enable toolbutton 
    ''' </summary>
    ''' <param name="bEnable"></param>
    ''' <remarks></remarks>
    Protected Overridable Sub SetEnableButtonOnToolbar(ByVal bEnable As Boolean)
        Try
            With ToolbarsManagerList.Tools
                .Item("mnuAdd").SharedProps.Enabled = True
                .Item("mnuEdit").SharedProps.Enabled = bEnable
                .Item("mnuView").SharedProps.Enabled = bEnable
                .Item("mnuDelete").SharedProps.Enabled = bEnable
                .Item("mnuRefresh").SharedProps.Enabled = True
                .Item("mnuPrint").SharedProps.Enabled = True
            End With
        Catch ex As Exception
            CommonFunction.ShowExceptionMessage(ex)
        End Try
    End Sub

    Protected Overridable Sub BindingSourcePositionChanged()
        If bsList.Position = - 1 Then
            SetEnableButtonOnToolbar(False)
        Else
            SetEnableButtonOnToolbar(True)
        End If
    End Sub

    Protected Overridable Function GetFormDetail() As frmBaseDictionaryDetail
        Dim frm As New frmBaseDictionaryDetail
        Return frm
    End Function

    Protected Overridable Sub ToolClick(ByVal tool As ToolBase)
        If tool.Key IsNot Nothing Then
            Select Case tool.Key
                Case "mnuAdd"
                    NewDictionary()
                Case "mnuEdit"
                    EditDictionary(False)
                Case "mnuView"
                    EditDictionary(True)
                Case "mnuDelete"
                    DeleteDictionary()
                Case "mnuRefresh"
                    RefreshData()
                Case "mnuPrint"

            End Select

        End If
    End Sub

#End Region

#End Region

#Region "Event"

#Region "Form event"

#End Region

#Region "Control event"

    Private Sub bsList_PositionChanged(ByVal sender As Object, ByVal e As EventArgs) Handles bsList.PositionChanged
        Try
            If Not IsLoadingData Then
                BindingSourcePositionChanged()
            End If
        Catch ex As Exception
            CommonFunction.ShowExceptionMessage(ex)
        End Try
    End Sub

    Private Sub grdList_DoubleClickRow(ByVal sender As Object, ByVal e As DoubleClickRowEventArgs) _
        Handles grdList.DoubleClickRow
        Try
            If e.Row.IsDataRow Then
                EditDictionary(True)
            End If
        Catch ex As Exception
            CommonFunction.ShowExceptionMessage(ex)
        End Try
    End Sub

    Private Sub grdList_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles grdList.KeyPress
        Try
            If e.KeyChar = Chr(Keys.Enter) Then
                e.Handled = True
                EditDictionary(True)
            End If
        Catch ex As Exception
            CommonFunction.ShowExceptionMessage(ex)
        End Try
    End Sub

    Private Sub ToolbarsManagerList_ToolClick(ByVal sender As Object, ByVal e As ToolClickEventArgs) _
        Handles ToolbarsManagerList.ToolClick
        Try
            Me.Cursor = Cursors.WaitCursor

            ToolClick(e.Tool)
        Catch ex As Exception
            CommonFunction.ShowExceptionMessage(ex)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

#End Region

#Region "User event"

    Protected Overridable Sub frmBaseDictionaryList_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Try
            Me.Cursor = Cursors.WaitCursor
            If Not Me.DesignMode Then
                InitPublicObject()
                InitDataToCombo()
                CommonFunction.AddRowCountToGrid(grdList)
                Me.SetEnableButtonOnToolbar(False)
                InitGridData()

                'CommonFunction.AddRowCountToGrid(grdList)

                'For Each oCol As UltraWinGrid.UltraGridColumn In grdList.DisplayLayout.Bands(0).Columns
                '    oCol.CellActivation = UltraWinGrid.Activation.ActivateOnly
                'Next

            End If
        Catch ex As Exception
            CommonFunction.ShowExceptionMessage(ex)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

#End Region

#End Region
End Class